<?php

require "../utility.php";

function addCartItemToDatabase(mysqli $conn, string $user_id, string $book_id, string $cnt): bool {
    $insert_str = "INSERT INTO Cart (bookID, userID, cnt) VALUES(?, ?, ?) ON DUPLICATE KEY UPDATE cnt = cnt + ?;";
    $insert_stmt = $conn->prepare($insert_str);
    $insert_stmt->bind_param("iiii", $book_id, $user_id, $cnt, $cnt);
    $status = $insert_stmt->execute();
    return $status;
}

$conn = connect_mysql();
$user_id = getUserIdBySessionId($conn);


http_response_code(403);

if ($user_id !== null &&
    check_keys($_GET, "bookID", "count")) {
    
    $book_id = $_GET["bookID"];
    $cnt = $_GET["count"];
    if (addCartItemToDatabase($conn, $user_id, $book_id, $cnt)) {
        // success
        http_response_code(200);
    }
}

$conn->close();

?>